//
//  STSerSetTableView.m
//  YiYueHairdresser
//
//  Created by zhouzhouzhou on 2018/9/30.
//  Copyright © 2018年 YuYiLian. All rights reserved.
//

#import "STSerSetView.h"
#import "TZImagePickerController.h"
#import "STSerMainImgCell.h"
#import "UIButton+WebCache.h"
#import "UIButton+ZYHblock.h"
#import "STSerChemicalCell.h"


@implementation STSerSetView

-(void)setSerViewWithData:(id)data{
    self.serviceModel = data;
    
    self.backgroundColor = [UIColor groupTableViewBackgroundColor];
    arrSetCells = [NSMutableArray arrayWithCapacity:0];
    if (!self.serviceTypeData.options.count) {
        arrSetCells =[NSMutableArray arrayWithArray:@[@2]];
    }else{
        arrSetCells = [NSMutableArray arrayWithArray:@[@3]];
        if(self.isLoadData && self.serviceModel.serviceOptions.count){
            for (int i =0 ;i<self.serviceModel.serviceOptions.count;i++) {
                STServiceOptionModel * optionModel =self.serviceModel.serviceOptions[i];
                int num = (int)optionModel.serviceOptionDetails.count?(int)optionModel.serviceOptionDetails.count:1;
                [arrSetCells addObject:@(num)];
            }
        }else{
            for (int i =0 ;i<self.serviceTypeData.options.count;i++) {
                [arrSetCells addObject:@1];
            }
        }
        
        [arrSetCells addObject:@1];
    }
    
    
    if(!serSetTableView){
        serSetTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-44) style:UITableViewStylePlain];
        serSetTableView.delegate = self;
        serSetTableView.dataSource = self;
        serSetTableView.separatorStyle = UITableViewCellSelectionStyleNone;
        serSetTableView.backgroundColor = [UIColor clearColor];
        [self addSubview:serSetTableView];
        [self addSubview:[self setFooterView:NO]];
    }else{
        [serSetTableView reloadData];
    }
    
}


-(UIView *)setFooterView:(BOOL)isFooter{
    UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-44, SCREEN_WIDTH, 44)];
    [btn setTitle:@"保存" forState:UIControlStateNormal];
    [btn setTintColor:[UIColor whiteColor]];
    btn.backgroundColor = [UIColor orangeColor];
    [btn addTarget:self action:@selector(actionSerSave) forControlEvents:UIControlEventTouchUpInside];
//    [footerView addSubview:btn];
    return btn;
}

-(void)setNewSelTimer{
    [serSetTableView reloadRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] withRowAnimation:NO];
}

-(void)setNewMainImg:(UIImage *)img{
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:(arrSetCells.count-1)];
    STSerMainImgCell * cell = [serSetTableView cellForRowAtIndexPath:indexPath];
    [cell.imgBtn setImage:img forState:UIControlStateNormal];
    self.serviceModel.mainImg = img;
    cell.delBtn.hidden = NO;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return arrSetCells.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSNumber * num = arrSetCells[section];
    return [num integerValue];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == (arrSetCells.count-1) && arrSetCells.count > 1 ) {
        return 150;
    }
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section <= (arrSetCells.count-2)) {
        return 44;
    }else{
        return 10;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section>0 && section<(arrSetCells.count-1)) {
        return 40;
    }
    return 0;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * addView = [[UIView alloc]init];
    addView.backgroundColor = [UIColor whiteColor];
    UIButton * addBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 5, 100, 30)];
    [addBtn setImage:[UIImage imageNamed:@"m-add"] forState:UIControlStateNormal];
    if(section>=1 && section<(arrSetCells.count-1)){
        STServiceOptionModel * model = self.serviceTypeData.options[section-1];
        [addBtn setTitle:model.optionbutton forState:UIControlStateNormal];
    }
    WeakSelf;
    addBtn.didSelectBtn = ^(UIButton * sender) {
        [weakSelf actionAddMore:section];
    };
    addBtn.titleLabel.font = FONT(13);
    [addBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    addBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    addBtn.layer.borderWidth = 1;
    [addView addSubview:addBtn];
    return addView;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * headerView = [UIView new];
    headerView.backgroundColor = [UIColor clearColor];
    UILabel * nameLab = [[UILabel alloc]initWithFrame:CGRectMake(10, 15, 100, 20)];
    nameLab.font = FONT(13);
    nameLab.textColor = [UIColor lightGrayColor];
    if (section > (arrSetCells.count-2)) {
        return headerView;
    }
    
    if (section == 0) {
        nameLab.text = [NSString stringWithFormat:@"服务类型:%@",self.serviceTypeData.name];
    }else if (section >= 1) {
        STServiceOptionModel * model = self.serviceTypeData.options[section-1];
        nameLab.text =model.optiontitle;
    }
    [headerView addSubview:nameLab];
    return headerView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WeakSelf
    UITableViewCell *cell;
    if(indexPath.section == 0){
        cell = [[NSBundle mainBundle] loadNibNamed:@"STTextCell" owner:nil options:nil].lastObject;
        UILabel * nameLab = (UILabel *)[cell viewWithTag:11001];
        UITextField * txt = (UITextField *)[cell viewWithTag:11002];
        UIView * line = (UIView *)[cell viewWithTag:11003];
        NSNumber * num = arrSetCells[indexPath.section];
        line.hidden = indexPath.row == ([num intValue] -1);
        txt.delegate = self;
        if (indexPath.row==0) {
            nameLab.text = @"服务所需时间:";
            txt.enabled = NO;
            txt.placeholder = @"请选择所需时间";
            if (self.serviceModel.duration) {
                txt.text = [NSString stringWithFormat:@"%0.1f小时",self.serviceModel.duration/60.0];
            }
        }else if (indexPath.row==1) {
            nameLab.text = @"服务所需价格:";
            txt.placeholder = @"请输入所需价格";
            txtPrice = txt;
            txtPrice.keyboardType = UIKeyboardTypeDecimalPad;
            if(self.serviceModel.price){
                txt.text= [NSString stringWithFormat:@"%0.2f",self.serviceModel.price];
            }
        }else if (indexPath.row==2) {
            nameLab.text = @"服务介绍:";
            txt.placeholder = @"请输服务介绍";
            txtIntroduce = txt;
            if(self.serviceModel.decription.length){
                txt.text=self.serviceModel.decription;
            }
        }
    }else if(indexPath.section <= (arrSetCells.count-2)){
        NSString * identifier = @"STSerChemicalCell";
        STSerChemicalCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[STSerChemicalCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        }
        STServiceOptionModel * serviceTypeModel = self.serviceTypeData.options[indexPath.section-1];
        
        STServiceOOModel * ooModel ;
        for (int j = 0; j<self.serviceModel.serviceOptions.count; j++) {
            STServiceOptionModel * modelData =self.serviceModel.serviceOptions[j];
            if(serviceTypeModel.objectId == modelData.optionId){
                if(modelData.serviceOptionDetails.count>indexPath.row){
                    ooModel = modelData.serviceOptionDetails[indexPath.row];
                }
                
            }
        }
        
            
        cell.txtName.delegate =self;
        cell.txtPrice.delegate =self;
        cell.delChemicalBtn = ^(UIButton * sender) {
          //删除
            [weakSelf actionDelChemical:indexPath];
        };
        [cell setChemicalsCellWithData:serviceTypeModel cellData:ooModel];
        
        return cell;
    }else if(indexPath.section ==(arrSetCells.count-1)){
        NSString * identifier = @"serMainImgCell";
        STSerMainImgCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[STSerMainImgCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        }
        if(self.serviceModel.picture){
            cell.delBtn.hidden = NO;
        }else{
            cell.delBtn.hidden = YES;
        }
        
        [cell.imgBtn sd_setImageWithURL:[NSURL URLWithString:self.serviceModel.picture] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"m-imgAdd"]];
        
        cell.didSelectBtn = ^(UIButton *sender) {
            [weakSelf actionSelMainImg];
        };
        cell.delSelectBtn = ^(UIButton *sender) {
            [weakSelf actionDelMainImg];
        };
        
        return cell;
    }
    cell.selectionStyle= UITableViewCellSelectionStyleNone;
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 0) {
        if ([self.delegate respondsToSelector:@selector(serSerSelTimer)]) {
            [self.delegate serSerSelTimer];
        }
    }
}

-(void)actionSerSave{
    if ([self.delegate respondsToSelector:@selector(serSetSaveWithData:)]) {
        [self.delegate serSetSaveWithData:self.serviceModel];
    }
}

-(void)actionAddMore:(NSInteger)section{
    
    NSNumber * num = arrSetCells[section];
    NSNumber * newNum = [NSNumber numberWithInteger:[num integerValue] +1];
    [arrSetCells replaceObjectAtIndex:section withObject:newNum];
    
    [self addServiceModelData:section];
    [serSetTableView reloadSection:section withRowAnimation:UITableViewRowAnimationFade];
}

-(void)addServiceModelData:(NSInteger)section{
    STServiceOptionModel * optionModel;
    if (self.serviceModel.serviceOptions.count<=(section-1)) {
        if(!self.serviceModel.serviceOptions){
            NSMutableArray * arr = [NSMutableArray arrayWithCapacity:0];
            self.serviceModel.serviceOptions = (NSMutableArray<STServiceOptionModel> *)arr;
        }
        optionModel = [STServiceOptionModel new];
        STServiceOptionModel * serviceModel = self.serviceTypeData.options[section-1];
        optionModel.optiontitle =serviceModel.optiontitle;
        optionModel.optionId =serviceModel.objectId;
        optionModel.optionname =serviceModel.optionname;
        optionModel.categoryId =serviceModel.categoryId;
        [self.serviceModel.serviceOptions addObject:optionModel];
    }else{
        optionModel =self.serviceModel.serviceOptions[section-1];
    }
    if(!optionModel.serviceOptionDetails.count){
        NSMutableArray * arr = [NSMutableArray arrayWithCapacity:0];
        optionModel.serviceOptionDetails = (NSMutableArray<STServiceOOModel> *)arr;
    }
    STServiceOOModel * ooModel = [STServiceOOModel new];
    
    int rowNum = [arrSetCells[section] intValue];
    for (int i=0; i<(optionModel.serviceOptionDetails.count-rowNum); i++) {
        [optionModel.serviceOptionDetails addObject:ooModel];
    }
    
}

-(void)actionDelChemical:(NSIndexPath *)indexPath{
    NSNumber * num = arrSetCells[indexPath.section];
    if (num<=0) {
        return;
    }
    if (self.serviceModel.serviceOptions.count) {
        STServiceOptionModel * optionModel =self.serviceModel.serviceOptions[indexPath.section-1];
        if(optionModel.serviceOptionDetails.count>indexPath.row){
            [optionModel.serviceOptionDetails removeObjectAtIndex:indexPath.row];
        }
    }
    
    NSNumber * newNum = [NSNumber numberWithInteger:[num integerValue] -1];
    [arrSetCells replaceObjectAtIndex:indexPath.section withObject:newNum];
    [serSetTableView reloadSection:indexPath.section withRowAnimation:UITableViewRowAnimationFade];
}

-(void)actionDelMainImg{
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:(arrSetCells.count-1)];
    STSerMainImgCell * cell = [serSetTableView cellForRowAtIndexPath:indexPath];
    [cell.imgBtn setImage:[UIImage imageNamed:@"m-imgAdd"] forState:UIControlStateNormal];
    self.serviceModel.mainImg = nil;
    cell.delBtn.hidden = YES;
}

-(void)actionSelMainImg{
   
    if ([self.delegate respondsToSelector:@selector(serSelMainImg)]) {
        [self.delegate serSelMainImg];
    }
}


- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    if (!textField.text.length) {
        return YES;
    }
    if ([textField isEqual:txtPrice]) {
        self.serviceModel.price = [textField.text floatValue];
    }else if ([textField isEqual:txtIntroduce]) {
        self.serviceModel.decription = textField.text;
    }else{
        UITableViewCell * cell = (UITableViewCell *)textField.superview.superview.superview;
        NSIndexPath * indexPath = [serSetTableView indexPathForCell:cell];
        STServiceOOModel * ooModel;
        STServiceOptionModel * serviceModel;
        if ( self.serviceModel.serviceOptions.count<=(indexPath.section-1)) {
            [self addServiceModelData:(indexPath.section)];
        }
        serviceModel = self.serviceModel.serviceOptions[indexPath.section-1];
        STServiceOptionModel * serviceTypeModel = self.serviceTypeData.options[indexPath.section-1];
        serviceModel.optionId =serviceTypeModel.objectId;
        if(!serviceModel.serviceOptionDetails.count){
            [self addServiceModelData:(indexPath.section)];
            STServiceOptionModel * initModel = self.serviceModel.serviceOptions[indexPath.section-1];
             ooModel =initModel.serviceOptionDetails[indexPath.row];
        }else{
             ooModel =serviceModel.serviceOptionDetails[indexPath.row];
        }
       
            
        if(textField.tag == 11014){
            ooModel.price =[textField.text floatValue];
        }else if(textField.tag == 11012){
            ooModel.optionvalue =textField.text;
        }
    }
    return YES;
    
}


@end
